package com.example.mweather;

import android.content.Intent;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.View;
import android.view.inputmethod.EditorInfo;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ViewAnimator;

import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.example.mweather.adapter.CityHotAdapter;
import com.example.mweather.adapter.CityResultAdapter;
import com.example.mweather.beans.SearchResult;
import com.google.gson.Gson;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

public class SearchActivity extends AppCompatActivity {

    private ViewAnimator vaSearch;
    private RecyclerView rvCityHot, rvCityResult;
    private ImageView ivBack, ivClear;
    private EditText edtSearch;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_search);
        ivBack = findViewById(R.id.ivBack);
        ivClear = findViewById(R.id.ivClear);
        vaSearch = findViewById(R.id.vaSearch);
        edtSearch = findViewById(R.id.edtSearch);
        rvCityResult = findViewById(R.id.rvCityResult);
        ivBack.setOnClickListener(v -> finish());
        ivClear.setOnClickListener(v -> {
            edtSearch.setText("");
            vaSearch.setDisplayedChild(0);
        });
        edtSearch.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                ivClear.setVisibility(s.length() > 0 ? View.VISIBLE : View.INVISIBLE);
            }
        });
        edtSearch.setOnEditorActionListener((v, actionId, event) -> {
            if (actionId == EditorInfo.IME_ACTION_SEARCH) {
                String key = edtSearch.getText().toString();
                doSearch(key);
                return true;
            }
            return false;
        });
        rvCityHot = findViewById(R.id.rvCityHot);
        rvCityHot.setLayoutManager(new GridLayoutManager(this, 3));
        List<String> cities = new ArrayList<>();
        cities.add("北京");
        cities.add("上海");
        cities.add("重庆");
        cities.add("广州");
        cities.add("深圳");
        cities.add("成都");
        cities.add("杭州");
        cities.add("三亚");
        cities.add("西安");
        cities.add("昆明");
        cities.add("长沙");
        cities.add("青岛");
        cities.add("南京");
        cities.add("海口");
        cities.add("武汉");
        rvCityHot.setAdapter(new CityHotAdapter(cities) {
            @Override
            public void selectCity(String city) {
                edtSearch.setText(city);
                doSearch(city);
            }
        });

    }

    /**
     * 执行搜索
     *
     * @param key
     */
    private void doSearch(String key) {
        vaSearch.setDisplayedChild(1);
        try {
            OkHttpClient client = new OkHttpClient();
            String url = "https://api.caiyunapp.com/v2/place?query=" + key + "&token=TAkhjf8d1nlSlspN&lang=zh_CN";
            Request request = new Request.Builder().url(url).build();
            client.newCall(request).enqueue(new Callback() {
                @Override
                public void onFailure(Call call, IOException e) {
                    e.printStackTrace();
                }

                @Override
                public void onResponse(Call call, Response response) throws IOException {
                    if (response.isSuccessful()) {
                        String repContent = response.body().string();
                        Gson gson = new Gson();
                        SearchResult searchResult = gson.fromJson(repContent, SearchResult.class);
                        runOnUiThread(() -> {
                            LinearLayoutManager layoutManager = new LinearLayoutManager(SearchActivity.this);
                            layoutManager.setOrientation(LinearLayoutManager.VERTICAL);
                            rvCityResult.setLayoutManager(layoutManager);
                            rvCityResult.setAdapter(new CityResultAdapter(searchResult.getPlaces()) {
                                @Override
                                public void selectPlace(SearchResult.PlacesDTO placesDTO) {
                                    Intent intent = new Intent(SearchActivity.this, WeatherResultActivity.class);
                                    intent.putExtra("city", placesDTO.getName());
                                    intent.putExtra("lng", placesDTO.getLocation().getLng());
                                    intent.putExtra("lat", placesDTO.getLocation().getLat());
                                    startActivity(intent);
                                }
                            });
                        });
                    } else {
                        Log.e(SearchActivity.this.getLocalClassName(), "获取城市数据失败");
                    }
                }
            });
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}